package com.ujoin.service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.ujoin.bean.Follow;
import com.ujoin.dao.imp.FollowDAO;
import com.ujoin.dao.imp.UserDAO;
import com.ujoin.util.JsonUtil;

/**
 * 
 * @author Daniel
 * 待测试
 *
 */
public class FollowService {
	@Autowired
	private FollowDAO followDao;
	
	@Autowired
	private UserDAO userDao;
	
	/**
	 * 关注（新建follow关系）
	 * @param follow
	 * @return Json
	 */
	public String createFollow(Follow follow){
		// 1 Check if followee and follower legal
		// 2 if not, report error
		// 3 else add to database
		JsonUtil jo = new JsonUtil();
		if ( userDao.findById(follow.getFolloweeId()) == null) {
			jo.getError();
			jo.setMessage("被关注者id不存在");
			return jo.toJSONString();
		}
		if ( userDao.findById(follow.getFollowerId()) == null) {
			jo.getError();
			jo.setMessage("关注者id不存在");
			return jo.toJSONString();
		}
		
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		follow.setCreated(timestamp);
		
		followDao.save(follow);
		
		jo.getSuccess();
		return jo.toJSONString();
	}
	
	/**
	 * 取消关注（删除关注关系）
	 * @param follow
	 * @return Json
	 */
    public String deleteFollow(Follow follow){
    	JsonUtil jo = new JsonUtil();
    	if ( userDao.findById(follow.getFolloweeId()) == null) {
			jo.getError();
			jo.setMessage("被关注者id不存在");
			return jo.toJSONString();
		}
		if ( userDao.findById(follow.getFollowerId()) == null) {
			jo.getError();
			jo.setMessage("关注者id不存在");
			return jo.toJSONString();
		}
		
		Follow f = followDao.findByUserIdPair(follow.getFollowerId(), follow.getFolloweeId());
		if ( f == null) {
			jo.getError();
			jo.setMessage("此关注关系不存在，无需删除");
		}
		
		followDao.delete(f);
		
		jo.getSuccess();
		return jo.toJSONString();
	}
    
    /**
     * 找粉丝
     * @param userId
     * @return Json
     */
    public String findFollower(int userId){
    	JsonUtil jo = new JsonUtil();
    	List list = followDao.findByFolloweeId(userId);
    	jo.getSuccess();
    	jo.setComponentList(list);
    	return jo.toJSONString();
	}
    
    /**
     * 找关注的人
     * @param userId
     * @return Json
     */
    public String findFollowee(int userId){
    	JsonUtil jo = new JsonUtil();
    	List list = followDao.findByFollowerId(userId);
    	jo.getSuccess();
    	jo.setComponentList(list);
    	return jo.toJSONString();
	}
}
